/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.sms.channel.aliyun;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lvyh.lightframe.sms.async.AsyncThreadPoolExecutor;
import com.lvyh.lightframe.sms.common.SmsMultipartContent;
import com.lvyh.lightframe.sms.processor.AbstractSmsPushProcessor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * Alibaba cloud SMS sending and processing
 *
 * @author lvyh 2021/03/13.
 */
@Slf4j
public class AliyunSmsPushProcessor extends AbstractSmsPushProcessor<AliyunProperties> {

    private static final String PRODUCT = "xxxsmsapi";

    private static final String DOMAIN = "xxxsmsapi.aliyuncs.com";

    private final ObjectMapper objectMapper;

    private final IAcsClient acsClient;

    private AsyncThreadPoolExecutor executor = new AsyncThreadPoolExecutor();

    public AliyunSmsPushProcessor(AliyunProperties properties) {
        super(properties);
        this.objectMapper = new ObjectMapper();
        IClientProfile profile = DefaultProfile.getProfile(properties.getRegionId(), properties.getAccessKeyId(), properties.getAccessKeySecret());
        DefaultProfile.addEndpoint(properties.getRegionId(), PRODUCT, DOMAIN);

        acsClient = new DefaultAcsClient(profile);
    }

    @Override
    public boolean sendMsg(SmsMultipartContent smsMsgContent, List<String> phones) {
        String paramString;
        try {
            paramString = objectMapper.writeValueAsString(smsMsgContent.getTemplateParams());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }

        SendSmsRequest request = new SendSmsRequest();
        request.setSysMethod(MethodType.POST);
        request.setPhoneNumbers(StringUtils.join(phones, ","));
        request.setSignName(properties.getSignName());
        request.setTemplateCode(smsMsgContent.getTemplateCode());//SMS_153055065
        request.setTemplateParam(paramString);//TemplateParam:{"name":"小陈","code":"123456"}，替换后模板内容："亲,${name},您的验证码为${code}..."

        try {
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            log.info("send sms result,code:{},message:{}", sendSmsResponse.getCode(), sendSmsResponse.getMessage());
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return false;
    }

    @Override
    public boolean asyncSendMsg(SmsMultipartContent smsMultipartContent, List<String> phones) {
        executor.submit(() -> asyncSend(smsMultipartContent, phones));
        return true;
    }

    @Override
    public String getChannelName() {
        return "aliyun";
    }
}
